package com.aatattoo.light_food_service.controller;

import com.aatattoo.light_food_service.config.error.ResultData;
import com.aatattoo.light_food_service.enumeration.ReturnCode;
import com.aatattoo.light_food_service.entity.Token;
import com.aatattoo.light_food_service.entity.User;
import com.aatattoo.light_food_service.entity.UserFollow;
import com.aatattoo.light_food_service.service.DynamicService;
import com.aatattoo.light_food_service.service.TokenService;
import com.aatattoo.light_food_service.service.UserFollowService;
import com.aatattoo.light_food_service.service.UserService;
import com.aatattoo.light_food_service.utils.TimeUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


import javax.websocket.server.PathParam;
import java.util.*;

@CrossOrigin
@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserFollowService userFollowService;
    @Autowired
    private DynamicService dynamicService;

    @GetMapping("/userInfo/{othUserId}")
    public Map<String,Object> getOthUserInfo(@PathVariable("othUserId")int userId){
        Map<String, Object> userMap = userService.getUserMap(userId);
        System.out.println(userMap);
        return userMap;
    }

    @GetMapping("/myFollow")
    public Map<String, Object> getMyFollow(@RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        List<UserFollow> userFollows = userFollowService.followFindById(userId);
        Map<String ,Object> map=new LinkedHashMap<>();
        map.put("countFollow",userFollows.size());
        List<Object> followList=new ArrayList<>();
        if (userFollows.size()==0){
            map.put("followList",followList);
        }else {
            userFollows.forEach(userFollow -> {
                Map<String,Object> userMap=new LinkedHashMap<>();
                int i = userFollowService.mutualAttentionFindById(userFollow);
                User user = userService.fingById(userFollow.getFollowId());
                System.out.println(userFollow.toString());
                userMap.put("id",userFollow.getId());
                userMap.put("userId",user.getId());
                userMap.put("name",user.getName());
                userMap.put("avatar",user.getAvatar());
                userMap.put("focusOnTime", TimeUtil.timestampFormat(userFollow.getCreateTime()));
                if (i==0){
                    userMap.put("mutualAttention",false);
                }else {
                    userMap.put("mutualAttention",true);
                }
                followList.add(userMap);
            });
            map.put("followList",followList);

        }
        return map;
    }

    @GetMapping("/myFans")
    public Map<String, Object> getMyFans(@RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        List<UserFollow> userFollows = userFollowService.fansFindById(userId);
        Map<String ,Object> map=new LinkedHashMap<>();
        map.put("countFans", userFollows.size());
        List<Object> fansList=new ArrayList<>();
        if (userFollows.size()==0){
            map.put("fansList",fansList);
        }else {
            userFollows.forEach(userFollow -> {
                Map<String,Object> userMap=new LinkedHashMap<>();
                int i = userFollowService.mutualAttentionFindById(userFollow);
                User user = userService.fingById(userFollow.getFansId());
                userMap.put("id",userFollow.getId());
                userMap.put("userId",user.getId());
                userMap.put("name",user.getName());
                userMap.put("avatar",user.getAvatar());
                userMap.put("focusOnTime", TimeUtil.timestampFormat(userFollow.getCreateTime()));
                if (i==0){
                    userMap.put("mutualAttention",false);
                }else {
                    userMap.put("mutualAttention",true);
                }
                fansList.add(userMap);
            });
            map.put("fansList",fansList);
        }
        return map;
    }

    @PostMapping("/follow")
    public int follow(@RequestBody UserFollow userFollow, @RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        userFollow.setFansId(userId);
        return userFollowService.addfollow(userFollow);
    }

    @PostMapping("/unFollow")
    public int unFollow(@RequestBody UserFollow userFollow, @RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        userFollow.setFansId(userId);
        return userFollowService.deletefollow(userFollow);
    }

    @GetMapping("/myId")
    public int getMyUserId(@RequestHeader("token")String token){
        return tokenService.analysisUserId(token);
    }

    @GetMapping("/userInfo")
    public Map<String,Object> getUserInfo(@RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        User user = userService.fingById(userId);
        Map<String,Object> map=new LinkedHashMap<>();
        map.put("id",userId);
        map.put("name",user.getName());
        map.put("gender",user.getGender());
        map.put("avatar",user.getAvatar());
        return map;
    }

    @GetMapping("/allUserInfo")
    public Map<String ,Object> getAllUserInfo(@RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        User user = userService.fingById(userId);
        int countFollow = userFollowService.countFollowById(userId);
        int countFans = userFollowService.countFansById(userId);
        int countDynamic = dynamicService.countDynamicByUserId(userId);
        Map<String,Object> map=new LinkedHashMap<>();
        map.put("id",userId);
        map.put("name",user.getName());
        map.put("gender",user.getGender());
        map.put("avatar",user.getAvatar());
        map.put("countFollow",countFollow);
        map.put("countFans",countFans);
        map.put("dynamic",countDynamic);
        return map;
    }

    @PostMapping("/checkPassword")
    public boolean checkPwd(@RequestBody User user,@RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        user.setId(userId);
        User byId = userService.fingById(userId);
        return user.getPwd().equals(byId.getPwd());

    }

    @PostMapping("/security")
    public int changeSecurity(@RequestBody User user,@RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        user.setId(userId);
        return userService.updataQuestionById(user);
    }

    @PostMapping("/name")
    public int changeName(@RequestBody User user,@RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        user.setId(userId);
        return userService.updataNameById(user);
    }

    @PostMapping("/gender")
    public int changeGender(@RequestBody User user,@RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        user.setId(userId);
        return userService.updataGenderById(user);
    }

    @PostMapping("/password")
    public int changePwdByPhone(@RequestBody User user,@RequestHeader("user")String phoneNumber){
        user.setPhoneNumber(phoneNumber);
        return userService.updataPwdByPhone(user);
    }

    @PostMapping("/passwordTo")
    public int changePwdByUserId(@RequestBody User user,@RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        user.setId(userId);
        return userService.updataPwdById(user);
    }

    @PostMapping("/answer")
    public boolean answerByPhone(@RequestBody User user,@RequestHeader("user")String phoneNumber){
        User byPhone = userService.findByPhone(phoneNumber);
        return user.getAnswer().equals(byPhone.getAnswer());
    }

    @PostMapping("/answerTo")
    public boolean answerByUserId(@RequestBody User user,@RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        User byId = userService.fingById(userId);
        return user.getAnswer().equals(byId.getAnswer());
    }

    @GetMapping("/security")
    public String securityQuestionByPhone(@RequestHeader("user")String phoneNumber){
        User byPhone = userService.findByPhone(phoneNumber);
        return byPhone.getQuestion();
    }

    @GetMapping("/securityTo")
    public String securityQuestionByUserId(@RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        User user = userService.fingById(userId);
        return user.getQuestion();
    }

    @PostMapping("/register")
    public int register(@RequestBody User user){
        return userService.addUser(user);
    }

    @PostMapping("/login")
    public Object login(@RequestBody User user){
        String tokenStr;
        Token token;
        if (userService.isTableExist(user.getPhoneNumber())==0){
            return ResultData.success("", ReturnCode.RC401,"登录失败，当前账号不存在");
        }
        User byPhone = userService.findByPhone(user.getPhoneNumber());
        if (byPhone.getPwd().equals(user.getPwd())){
            Date date = new Date();
            int nowTime = (int) (date.getTime() / 1000);
            //生成Token
            tokenStr = tokenService.creatToken(byPhone.getId(), date);
            //根据数据库的用户信息查询Token
            if (tokenService.isTableExist(byPhone.getId())==0){
                //第一次登陆
                token = new Token();
                token.setToken(tokenStr);
                token.setBuildTime(nowTime);
                token.setUserId(byPhone.getId());
                tokenService.addToken(token);
            }else{
                token = tokenService.findByUserId(byPhone.getId());
                //登陆就更新Token信息
                token.setToken(tokenStr);
                token.setBuildTime(nowTime);
                tokenService.updataToken(token);
            }
            return ResultData.success(tokenStr, ReturnCode.RC200,"登录成功");
        }else{
            return ResultData.success("", ReturnCode.RC401,"登录失败，密码错误");
        }

    }

    @PostMapping("/checkUser")
    public boolean checkUser(@RequestBody User user){
        return !(userService.isTableExist(user.getPhoneNumber())==0);

    }

    @GetMapping("/authentication")
    private boolean authentication(@RequestHeader("token")String token){
        Claims claims = Jwts.parser().setSigningKey("account").parseClaimsJws(token).getBody();
        Date tokenDate=claims.getExpiration();
        int overTime=(int)(System.currentTimeMillis()-tokenDate.getTime())/1000;
        int tokenTime=60*60*24*3;
        return overTime>tokenTime;
    }

}